import { useBoolean } from 'ahooks';
import { useState } from 'react';
/**
 * 获取验证码
 * @param preCountFunc 发送验证码之前
 * @param postCountFunc 发送验证码之后
 * @returns { handleCountBackwards, count }
 */
const useHandleCountBackwards = (
  preCountFunc: () => void,
  postCountFunc: () => void
) => {
  const [count, setCount] = useState<number>(60);
  const [isTiming,
    {
      setTrue: startTiming,
      setFalse: endTiming
    }] = useBoolean(false); // 是否正在计时
  const handleCountBackwards = () => {
    let tempCount = 60;
    startTiming();
    preCountFunc();
    const countInterval = setInterval(() => {
      if (tempCount <= 0) {
        postCountFunc();
        tempCount = 60;
        endTiming();
        clearInterval(countInterval);
      }
      tempCount -= 1;
      setCount(tempCount);
    }, 1000);
  };

  return { handleCountBackwards, count, isTiming };
};

export default useHandleCountBackwards;
